package com.anzuo.app.ui.main

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anzuo.app.data.model.Item
import com.anzuo.app.data.repository.HomeRepository
import kotlinx.coroutines.launch

/**
 * HomeViewModel - 首页ViewModel
 * 负责处理业务逻辑和数据管理
 * 
 * @author AnZuo
 * @date 2024
 */
class HomeViewModel(
    private val repository: HomeRepository = HomeRepository()
) : ViewModel() {

    // 使用MutableLiveData存储可变数据，对外暴露LiveData
    private val _items = MutableLiveData<List<Item>>()
    val items: LiveData<List<Item>> = _items

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> = _isLoading

    init {
        // ViewModel创建时加载数据
        loadData()
    }

    /**
     * 加载数据
     */
    fun loadData() {
        viewModelScope.launch {
            try {
                _isLoading.value = true
                val result = repository.getItems()
                _items.value = result
            } catch (e: Exception) {
                // 处理错误
                e.printStackTrace()
            } finally {
                _isLoading.value = false
            }
        }
    }

    /**
     * 刷新数据
     */
    fun refresh() {
        loadData()
    }
}

